package netWork;

import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

//客户端
public class UdpEchoClient {
    private String ServerIp;
    private int ServerPort;

    private DatagramSocket socket = null;

    public UdpEchoClient(String ip , int port) throws SocketException {
       //不需要指定端口号
        socket = new DatagramSocket();
        this.ServerIp = ip;
        this.ServerPort = port;
    }

    public static void main(String[] args) throws IOException {

        UdpEchoClient client = new UdpEchoClient("127.0.0.1",4444);
        client.start();
    }
    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.println("请输入请求");
            //输入请求
            String request = scanner.next();
            //根据请求和ip端口号创建数据包
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), request.getBytes(StandardCharsets.UTF_8).length,
                    InetAddress.getByName(ServerIp),ServerPort);
            //将数据包内容发送过去
            socket.send(requestPacket);
            //创建新的数据包
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4096);
            //将socket接受到的信息写入到数据包中
            socket.receive(responsePacket);
            //将数据包中的内同显示出来
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength());

            System.out.printf("[%s:%d] req: %s ,resp %s\n", requestPacket.getAddress().toString(), requestPacket.getPort(), request, response);
            //关闭客户端

        }

    }
}
